package com.fqy.ticket.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fqy.ticket.business.domain.DailyTrain;
import com.fqy.ticket.business.domain.DailyTrainExample;
import com.fqy.ticket.business.domain.Train;
import com.fqy.ticket.business.mapper.DailyTrainMapper;
import com.fqy.ticket.business.req.DailyTrainQueryReq;
import com.fqy.ticket.business.req.DailyTrainSaveReq;
import com.fqy.ticket.business.resp.DailyTrainQueryResp;
import com.fqy.ticket.common.resp.PageResp;
import com.fqy.ticket.common.util.SnowUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DailyTrainService {

    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainService.class);

    @Resource
    private DailyTrainMapper dailyTrainMapper;

    @Resource
    private TrainService trainService;

    @Resource
    private DailyTrainStationService dailyTrainStationService;
    @Resource
    private DailyTrainCarriageService dailyTrainCarriageService;
    @Resource
    private DailyTrainSeatService dailyTrainSeatService;
    @Resource
    private DailyTrainTicketService dailyTrainTicketService;

    @Resource
    private SkTokenService skTokenService;

    /**
     * 保存DailyTrain记录（新增或更新）
     * @param req 保存请求对象
     */
    public void save(DailyTrainSaveReq req) {
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(req, DailyTrain.class);

        if (ObjectUtil.isNull(dailyTrain.getId())) {
            // 新增逻辑
            dailyTrain.setId(SnowUtil.getSnowflakeNextId());
            dailyTrain.setCreateTime(now);
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.insert(dailyTrain);
            LOG.info("新增DailyTrain成功，ID：{}", dailyTrain.getId());
        } else {
            // 更新逻辑
            dailyTrain.setUpdateTime(now);
            dailyTrainMapper.updateByPrimaryKey(dailyTrain);
        }
    }

    /**
     * 分页查询DailyTrain列表
     * @param req 查询请求对象（包含分页信息）
     * @return 分页结果
     */
    public PageResp<DailyTrainQueryResp> queryList(DailyTrainQueryReq req) {
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.setOrderByClause("`date` desc, code desc");
        DailyTrainExample.Criteria criteria = dailyTrainExample.createCriteria();

        if (ObjectUtil.isNotEmpty(req.getCode())) {
            criteria.andCodeEqualTo(req.getCode());
        }

        if (ObjectUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }


        LOG.info("查询DailyTrain列表，页码：{}，每页条数：{}", req.getPage(), req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrain> dailyTrainList = dailyTrainMapper.selectByExample(dailyTrainExample);

        PageInfo<DailyTrain> pageInfo = new PageInfo<>(dailyTrainList);
        LOG.info("查询结果：总行数={}，总页数={}", pageInfo.getTotal(), pageInfo.getPages());

        List<DailyTrainQueryResp> list = BeanUtil.copyToList(dailyTrainList, DailyTrainQueryResp.class);

        PageResp<DailyTrainQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除DailyTrain记录
     * @param id 记录ID
     */
    public void delete(Long id) {
        int count = dailyTrainMapper.deleteByPrimaryKey(id);
    }

    /*
    * 生成某日所有车次信息，包括，车次，车站，车厢，座位
    **/
    @Transactional
    public void genDaily(Date date) {
        // 查询所有火车信息
        List<Train> trains = trainService.selectAll();
        if (CollUtil.isEmpty(trains)) {
            LOG.info("没有车次基础数据,任务结束");
            return;
        }
        // 对每个车次循环生成
        for (Train train : trains) {
            // 生成每日车次信息
            genDailyTrain(date, train);
        }
    }

    public void genDailyTrain(Date date, Train train) {
        LOG.info("生成日期【{}】车次【{}】的信息开始", DateUtil.formatDate(date), train.getCode());

        // 删除该车次旧数据
        DailyTrainExample dailyTrainExample = new DailyTrainExample();
        dailyTrainExample.createCriteria()
                .andDateEqualTo(date)
                .andCodeEqualTo(train.getCode());
        dailyTrainMapper.deleteByExample(dailyTrainExample);

        // 生成该车次数据
        DateTime now = DateTime.now();
        DailyTrain dailyTrain = BeanUtil.copyProperties(train, DailyTrain.class);
        // 重新生成id,不要和train保持一致,因为同一个train会有多个日期的车次
        dailyTrain.setId(SnowUtil.getSnowflakeNextId());
        dailyTrain.setUpdateTime(now);
        dailyTrain.setCreateTime(now);
        dailyTrain.setDate(date);

        String code = train.getCode();

        // 生成该车次的车站数据
        dailyTrainStationService.genDaily(date, code);
        // 生成该车次的车厢数据
        dailyTrainCarriageService.genDaily(date, code);
        // 生成该车次的座位数据
        dailyTrainSeatService.genDaily(date, code);
        // 生成该车次的余票数据
        dailyTrainTicketService.genDaily(dailyTrain, date, code);

        // 生成令牌余量数据
        skTokenService.genDaily(date, train.getCode());

        dailyTrainMapper.insert(dailyTrain);

        LOG.info("生成日期【{}】车次【{}】的信息结束", DateUtil.formatDate(date), train.getCode());
    }
}